/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.hutech09.jsale.web.manager.product;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import org.hutech09.jsale.bsn.IProductManager;
import org.hutech09.jsale.bsn.exception.ItemNotFoundException;
import org.hutech09.jsale.entity.Product;
import org.hutech09.jsale.entity.ProductImage;
import org.hutech09.jsale.web.manager.AppConstrant;
import org.primefaces.event.FileUploadEvent;

/**
 *
 * @author Nam
 */
@ManagedBean
@RequestScoped
public class ImageUploadListener {

    @EJB
    private IProductManager productMgr;

    @ManagedProperty("#{productBrowseCtrl}")
    private ProductBrowseCtrl productBrowse;

    public void handleFileUpload(FileUploadEvent event) {
        String fileType = event.getFile().getFileName().substring(event.getFile().getFileName().length() - 4, event.getFile().getFileName().length() );
        
        Product pro = productBrowse.getSelected();
        ProductImage image = new ProductImage();
        image.setProduct(pro);
        image = productMgr.addImage(image);
        String imageName = image.getId().toString() + fileType;
        image.setImagePath(imageName);
        try {
            image = productMgr.updateImage(image);
        } catch (ItemNotFoundException ex) {
            Logger.getLogger(ImageUploadListener.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        try {
            File targetFolder = new File(AppConstrant.IMAGE_DIRECTORY);
            InputStream inputStream = event.getFile().getInputstream();
            OutputStream out = new FileOutputStream(new File(targetFolder, imageName));

            int read = 0;
            byte[] bytes = new byte[1024];
            while ((read = inputStream.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            inputStream.close();
            out.flush();
            out.close();


        } catch (IOException ex) {
            Logger.getLogger(ImageUploadListener.class.getName()).log(Level.SEVERE, null, ex);
        }


        System.out.println("file upload: " + event.getFile().getFileName());

        FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    public void setProductBrowse(ProductBrowseCtrl productBrowse) {
        this.productBrowse = productBrowse;
    }
}
